﻿using hpcpdi.DataAccess.Base;
using hpcpdi.DataAccess.Interface;
using hpcpdi.Entities;
using hpcpdi.Entities.DTO;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace hpcpdi.DataAccess.Impl
{
    public class TargetRepository : ITargetRepository
    {
        private readonly Context _context;

        public TargetRepository(Context context)
        {
            _context = context;
        }
        public async Task<int> GetTotalTarget()
        {
            return await _context.Target.CountAsync(s => s.Visibility == true);
        }
        public async Task<int> GetLaneChangeTarget()
        {
            return await _context.Target.CountAsync(s => s.Visibility == true && s.IsLaneChange == true);
        }

        public async Task<int> GetRetrogradeTarget()
        {
            return await _context.Target.CountAsync(s => s.Visibility == true && s.IsRetrograde == true);
        }

        public async Task<int> GetSlowMoveTarget()
        {
            return await _context.Target.CountAsync(s => s.Visibility == true && s.IsSlowMove == true);
        }

        public async Task<int> GetStopTarget()
        {
            return await _context.Target.CountAsync(s => s.Visibility == true && s.IsStop == true);
        }

        public speedVM GetSpeed()
        {
            return _context.Database.SqlQuery<speedVM>("select AVG(speed) as avgSpeed,max(speed) as maxSpeed,min(Speed) as minSpeed from target where Visibility=1").FirstOrDefault();
        }

        public int GetSuddenlyCLCome() {
            return _context.trafficpass_cur.FirstOrDefault().SuddenlyCLCome;
        }
        public int GetSuddenlyCLGo()
        {
            return _context.trafficpass_cur.FirstOrDefault().SuddenlyCLGo;
        }

        public int GetSuddenlyStopCome()
        {
            return _context.trafficpass_cur.FirstOrDefault().SuddenlyStopCome;
        }
        public int GetSuddenlyStopGo()
        {
            return _context.trafficpass_cur.FirstOrDefault().SuddenlyStopGo;
        }
        public earlyWarningVM GetEarlyWarning()
        {
            string sql = @"select cast(sum(SuddenlyStopCome+SuddenlyStopGo) as SIGNED ) as SuddenlyStop, cast(sum(SuddenlyCLCome+SuddenlyCLGo) as SIGNED) as SuddenlyCL
, Restrograde, SlowMoving, OtherWorning from trafficpass_cur ";
            return _context.Database.SqlQuery<earlyWarningVM>(sql).FirstOrDefault();
        }
        public IEnumerable<trafficpass_his> GetTrafficPassValue(int days) {
            return _context.trafficpass_his.OrderByDescending(s=>s.Id).Take<trafficpass_his>(days).DefaultIfEmpty();
        }

    }
}
